import { makeAutoObservable, } from "mobx";
import { showError } from "../components/Message";
import { ArticleCategory, ResearchCategoryService, ResearchCollectService, ResearchData, ResearchItem, ResearchLatestService, ResearchService } from "../services/ResearchService";

class ResearchStore {
  public categories: ArticleCategory[] = [];
  public list: ResearchItem[] = [];
  public latestList: ResearchItem[] = [];
  public loading: boolean = false;
  public type: string = '';
  public keyword: string = '';
  private _page = 1;
  public loadingMore: boolean = false;
  public loadingLatest: boolean = false;
  private noMore: boolean = false;

  constructor() {
    makeAutoObservable(this);
  }

  public async getLatest() {
    if (this.loadingLatest) {
      return;
    }
    let response: ResearchData;

    this.loadingLatest = true;

    try {
      response = await new ResearchLatestService().send();
    } catch (e: any) {
      this.loadingLatest = false;
      showError(e);
      return;
    }
    this.loadingLatest = false;
    this.latestList = response.list;
  }



  public async getData(loadmore: boolean = false) {
    if (this.loading || this.loadingMore) {
      return;
    }
    let response: ResearchData;
    if (!this.type) {
      await this.getCategory();
    }
    if (loadmore) {
      if (this.noMore) {
        return;
      }
      this.loadingMore = true;
      this._page += 1;
    } else {
      this.loading = true;
      this._page = 1;
    }
    try {
      if (this.type === 'collect') {
        response = await new ResearchCollectService(this._page).send();
      } else {
        response = await new ResearchService('', '', this.keyword, this.type, this._page).send();
      }
    } catch (e: any) {
      this.loading = false;
      this.loadingMore = false;
      showError(e);
      return;
    }
    this.loading = false;
    this.loadingMore = false;
    if (loadmore) {
      this.noMore = response.list.length === 0;
      this.list.push(...response.list);
    } else {
      this.list = response.list;
    }
  }

  public async getCategory() {
    try {
      this.categories = await new ResearchCategoryService().send();
    } catch (e: any) {
      showError(e);
      return;
    }
    this.type = this.categories.map((c) => c.id).join(",");
  }

  public async changeType(type: string) {

    if (!type) {
      this.type = this.categories.map((c) => c.id).join(",");
    } else {
      this.type = type;
    }
    this._page = 1;
    this.noMore = false;
    this.getData();
  }

  public async search(key: string) {
    this.keyword = key;
    this.getData();
  }

}

const researchStore = new ResearchStore();

export { researchStore };